/*
	网站页面控制器
*/
var avArticle		= AV.Object.extend("Article");
var avContentGroup	= AV.Object.extend("ContentGroup");
var avImage 		= AV.Object.extend("Image");
var avPage			= AV.Object.extend("Page");
var avTemplet		= AV.Object.extend("Templet");

var moment		= require('moment');
var fs 			= require('fs');
var mdCommon	= require('cloud/modules/common.js');

var display		= function(res,tplFile,data) {
	data.moment		= moment;
	data.layout		= false;
	mdCommon.display(res,tplFile,data);
}

/**
 * 用户登录
 * 2015.05.15  by 胡斌
 */
exports.doLogin = function(req,res) {
	var queryUser = new AV.Query(AV.User);
	queryUser.equalTo("email",req.body.email);
	queryUser.first().then(function(user){
		if(typeof(user)=="undefined"){
			return AV.Promise.error('用户不存在');//登录失败
		}else{
			var crypto 	= require('crypto');  
			var md5 	= crypto.createHash('md5');
			md5.update(req.body.password);
			return AV.User.logIn(user.get("username"), md5.digest('hex'));
		}
	}).then(function(username) {
		//跳转到profile页面。
		res.redirect('/member');
    },function(error) {
		if(typeof(error)=="object"){
			error=error.message;
		}
		//登录失败，跳转到登录页面
		res.redirect('/member',{
			error:error
		});
	});
}

/**
 * 用户登出
 * 2015.05.15  by 胡斌
 */
exports.doLogout = function(req,res) {
	AV.User.logOut();
    res.redirect('/member');
}

/**
 * 新增用户
 * 2015.05.15  by 胡斌
 */
exports.doCreateUser = function(req,res) {
	var User;
	var name		= req.body.name;
	var email		= req.body.email;
	var mobile		= req.body.mobile;
	var qq			= req.body.qq;
	var password	= req.body.password;
	var queryUser 	= new AV.Query(AV.User);
	queryUser.equalTo("username",name);
	queryUser.count().then(function(count){
		if(count>0){
			return AV.Promise.error('该用户名已存在！');//
		}else{
			queryUser 	= new AV.Query(AV.User);
			queryUser.equalTo("email",email);
			return queryUser.count();
		}
	}).then(function(count){
		if(count>0){
			return AV.Promise.error("该邮箱已存在！");
		}else{
			console.dir(req.body);
			var newUser = new AV.User();
			var crypto 	= require('crypto');  
			var md5 	= crypto.createHash('md5');
			md5.update(password);
			
			newUser.set("password",md5.digest('hex'));
			newUser.set("username",name);
			newUser.set("email",email);
			newUser.set("roleName","user");
			if(mobile)newUser.set("mobile",mobile);
			if(qq)newUser.set("qq",mobile);
			
			return newUser.save();
		}
	}).then(function(result) {
		User			= result;
		var queryRole 	= new AV.Query(AV.Role);
		queryRole.equalTo("name","user");
		return queryRole.first();
    }).then(function(Role){
		if(typeof(Role)=="undefined"){
			return AV.Promise.error('默认角色不存在！');//
		}else{
			Role.getUsers().add(User);
			return Role.save();
		}
    }).then(function(Role) {
		res.redirect('/member');
    },function(error) {
		if(typeof(error)=="object"){
			error=error.message;
		}
		display(res,"message",{
			user:req.AV.user,
			result:req.AV.user,
			message:error
		});
	});
}

